from fastapi import APIRouter,Depends
from sqlalchemy import desc
from sqlalchemy.orm import Session
from db.mysql import get_db
from model.equipment_sensor import EquipmentSensorTable
from model.equipment_drill import EquipmentDrill
from model.equipment import Equipment
from vendor.extend.courier import *
from vendor.extend.conversion import is_positive_integer
from model.downmine_data import DownmineData
from vendor.library.many_points_stress.sort_point import process_wavelength_data
ConfigurationSensor = APIRouter()

@ConfigurationSensor.get('/monitor')
async def monitor(equipment_id:int, db: Session = Depends(get_db)):
    if not is_positive_integer(equipment_id):
        return Error(msg='工作面ID必须为正整数')
    query = db.query(EquipmentSensorTable, Equipment, EquipmentDrill).join(Equipment, Equipment.id == EquipmentSensorTable.equipment_id).join(EquipmentDrill, EquipmentSensorTable.drill_id == EquipmentDrill.id)
    results = query.filter(Equipment.id==equipment_id).order_by(EquipmentSensorTable.id.desc()).all()
    sensor=[]
    # 遍历结果
    for row,info,drill in results:
        disabled=None
        if drill.channel:
            # 传入的通道名称数据
            channel_num = drill.channel.lower()
            ch2 = drill.channel[:2]
            if ch2 =='ch':
                last_data=db.query(DownmineData.line,DownmineData.data).filter_by(line=channel_num).order_by(desc("id")).first()
                if last_data:
                    # 传入的点数
                    point_num = 10
                    raw_wavelength_data={}
                    # 传入的设计波长 后台配置
                    design_wavelengths = [1529.948, 1533.435,  1540.348, 1536.698, 1547.937, 1543.769, 1551.826, 1555.261, 1558.858, 1562.280]
                    # 波长数据
                    raw_wavelength_data[last_data.line]=last_data.data
                    # 运行处理
                    analysis_report, processed_data, need_analysis, abnormal_positions= process_wavelength_data(design_wavelengths, raw_wavelength_data, point_num, channel_num)
                    #disabled = [(index+1) for index, item in enumerate(processed_data) if item == None]
                    disabled=[]

        sensor.append({
            "equipment_id":info.id,
            "sensor_id":row.id,
            "drill_id":drill.id,
            "sensor_numbering":row.numbering,
            "drill_line":drill.line,
            "drill_identifier":drill.identifier,
            "drill_type":drill.type,
            'dead_pixel':disabled,
            "drill_channel":drill.channel,
            "drill_x":drill.x,
            "drill_y":drill.y,
            "drill_z":drill.z
        })


    return Success(data=sensor)